<?php

namespace app\task\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;

/**
 * 充值失败订单自动退款.
 */
class AutoCancel extends Command
{


    /**
     * 配置指令.
     */
    protected function configure()
    {
        $this->setName('coupon:autoCancel')
            ->setDescription('coupon order auto cancel');
    }

    /**
     * 执行指令.
     *
     * sudo -u www php /www/wwwroot/api/think coupon:autoCancel
     *
     * @throws \think\admin\Exception
     */
    protected function execute(Input $input, Output $output)
    {

        return  true;
        echo '权益订单自动取消--'.PHP_EOL;
        $lockKey = 'coupon_order_auto_cancel_lock_key';
        $lockVal = cache($lockKey);
        if ($lockVal) {
            echo '还在处理呢'.PHP_EOL;

             return true;
        }
        $countdown=WAIT_PAY_TIME;
        $time=date("Y-m-d H:i:s",strtotime("-$countdown minutes"));
        cache($lockKey, 1, 120);
        $where=[];
        $where[]=['pay_status',"=",0];
        $where[]=['status',"<>",10];
        $where[]=['created_at',"<",$time];
        $list = Db::name('coupon_order')
            ->where($where)
            ->limit(30)
            ->order('id asc')
            ->select()
            ->toArray();

        $done = 0;
        foreach ($list as $order) {
             Db::name("coupon_order")->where("id",$order['id'])->update(['status'=>10]);
             Db::name("coupon_pay_log")->where("order_id",$order['order_id'])->update(['status'=>3]);
             $done++;
        }

        cache($lockKey, null);

        echo '成功取消权益订单：'.$done.' 单'.PHP_EOL;
    }
}
